package cn.acac.yygh.gateway.filter;


import com.google.common.net.HttpHeaders;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局过滤器
 */
// @Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    // 路径匹配规则
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取访问路径
        String path = request.getURI().getPath();
        // 判断访问路径是否有指定路径
        if(antPathMatcher.match("/admin/user/**",path)){
            // 放行
            return chain.filter(exchange);
        }else{  // 对于非登录接口的访问，我们需要验证后才能确认是否放行
            List<String> strings = request.getHeaders().get("X-Token");
            // 判断集合是否为空
            if(strings == null){
                // 未登录，跳转到登录页面
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                // 路由跳转
                response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:9528");
                // 结束请求
                return response.setComplete();
            }else {
                // 放行
                return chain.filter(exchange);
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
